/*  This file is part of -_-.

    -_- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    -_- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with -_-.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2012-2013 Oliver Katz */

#include "mod_ipc_server.h"

namespace sleepyface
{
    namespace arch
    {
        namespace modules
        {
            IPCServer::IPCServer() : ArchModule()
            {
                setName("ipc-server");
            }

            ModuleValue IPCServer::get(string k0, string k1, Architecture &a)
            {
                if (k0.empty())
                {
                    z_data req = z_ipc_server_wait(&server, &port, &ip);
                    z_data *tmp = (z_data *)malloc(sizeof(z_data));
                    *tmp = req;
                    return ModuleValue(ModuleValue::_data, tmp);
                }
                else if (k0.compare("port") == 0)
                {
                    return ModuleValue(ModuleValue::_int, port);
                }
                else if (k0.compare("ip") == 0)
                {
                    return ModuleValue(ModuleValue::_string, string(ip));
                }
                else
                {
                    return ModuleValue();
                }
            }

            ModuleValue IPCServer::set(string k0, string k1, ModuleValue v, Architecture &a)
            {
                z_data *res = (z_data *)v.getData();
                if (z_ipc_server_reply(&server, res) != 0)
                    return ModuleValue();
                else
                    return v;
            }

            int IPCServer::signal(ModuleSignal s, Architecture &a)
            {
                if (s.getCode() == signalInitialize)
                {
                    return 0;
                }
                else if (s.getCode() == signalUninitialize)
                {
                    z_ipc_server_disconnect(&server);
                    z_ipc_server_release(server);
                    return 0;
                }
                else if (s.getCode() == signalConnect)
                {
                    server = z_ipc_server_init_global(s.getData(0).getInt());
                    return z_ipc_server_connect(&server);
                }
                else
                {
                    return 0;
                }
            }
        }
    }
}
